import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from './user.interface';
import { CreateUserDTO, EditUserDTO } from './user.dto';

@Injectable()
export class UserService {
  constructor(@InjectModel('Users') private readonly userModel: Model<User>) {}

  /**
   * 查找所有用户
   */
  async findAll(): Promise<User[]> {
    const users = await this.userModel.find();
    return users;
  }

  /**
   * 根据_id查找用户
   * @param _id
   */
  async findOne(_id: string): Promise<User> {
    const user = await this.userModel.findById(_id);
    return user;
  }

  /**
   * 添加用用户
   * @param body 用户信息
   */
  async addOne(body: CreateUserDTO): Promise<void> {
    await this.userModel.create(body);
  }

  /**
   * 编辑用户信息
   * @param _id 用户id
   * @param body 用户信息
   */
  async editOne(_id: string, body: EditUserDTO): Promise<void> {
    await this.userModel.findByIdAndUpdate(_id, body);
  }

  /**
   * 根据id删除用户
   * @param _id 用户id
   */
  async deleteOne(_id: string): Promise<void> {
    await this.userModel.findByIdAndDelete(_id);
  }

  /**
   * 分页查询
   * @param pageNum 第几页
   * @param pageSize  每页数据条数
   */
  async findPage(pageNum: number, pageSize: number): Promise<User[]> {
    const userList = this.userModel
      .find()
      .skip((pageNum - 1) * pageSize)
      .limit(pageSize);
    return userList;
  }

  async findCount(): Promise<number> {
    const users = await this.userModel.count();
    return users;
  }
}
